package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("SpiderService")
@Transactional

public class SpiderServiceImpl extends CmiEmaService implements SpiderService {
	public SpiderServiceImpl() {
	}

	@Transactional
	public Spider saveSpider(Spider spider) {

		if (spider.getId() == null) {

			Spider existingSpider = spiderDAO.findSpiderByPhysicalPrimaryKey(spider.getName());

			if (isEquals(spider, existingSpider)) {
				return existingSpider;
			}

			spider = spiderDAO.store(spider);
			spiderDAO.flush();

		} else {
			Spider existingSpider = spiderDAO.findSpiderByPrimaryKey(spider.getId());

			spider = spiderDAO.store(spider);
			spiderDAO.flush();
		}

		return spider;
	}

	public void deleteSpider(Spider spider) {
		spiderDAO.remove(spider);
		spiderDAO.flush();
	}

	@Transactional
	public void deleteSpiders(Set<Integer> deleteSpidersId) {
		Query query = spiderDAO.createNamedQuery("deleteSpidersById", -1, -1);
		query.setParameter(1, deleteSpidersId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Spider> loadSpiders() {
		return spiderDAO.findAllSpiders();

	}

	@Transactional
	public Set<Spider> loadReferenceSpiders(Set<Spider> spiders) {
		Iterator<Spider> spidersIterator = spiders.iterator();
		Set<Spider> referencedSpiders = new HashSet<>();
		while (spidersIterator.hasNext()) {
			Spider currentSpider = spidersIterator.next();

		}
		return referencedSpiders;
	}

	public Set<Spider> loadSpidersByIdSet(Set<Integer> spiderIdSet) {

		Iterator<Integer> spiderIdIterator = spiderIdSet.iterator();
		Set<Spider> spiderSet = new HashSet<>();
		while (spiderIdIterator.hasNext()) {
			Integer id = spiderIdIterator.next();
			Spider currentSpider = spiderDAO.findSpiderById(id);
			spiderSet.add(currentSpider);
		}
		return spiderSet;
	}

	@Transactional
	public List<Spider> findAllSpiders(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Spider>(spiderDAO.findAllSpiders(startResult, maxRows));
	}

	@Transactional
	public Spider findSpiderByPrimaryKey(Integer id) {
		return spiderDAO.findSpiderByPrimaryKey(id);
	}

	@Transactional
	public Integer countSpiders() {
		return ((Long) spiderDAO.createQuerySingleResult("select count(o) from Spider o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countSpiders(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Spider.class);
		return ((Long) spiderDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countSpidersByName(String queryName) {
		Query query = spiderDAO.createNamedQuery("countSpidersByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countSpidersByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Spider.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadSpiderObjectReferencedSet(Spider spider) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadSpiderClassReferencedSet(Spider spider) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();

		return classReferencedSetMap;
	}

	public boolean isEquals(Spider spider, Object obj) {
		if (obj == spider)
			return true;
		if (!(obj instanceof Spider))
			return false;
		Spider comparedSpider = (Spider) obj;
		if (!CheckPropertyEqual(spider.getName(), comparedSpider.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

